package com.naiterui.ehp.bs.recommend.func;


import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;

import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bs.recommend.bean.RecomAuditConfig;
import com.naiterui.ehp.bs.recommend.exception.ExceptionCodes;
import com.naiterui.ehp.bs.recommend.repository.mysql.IRecomAuditConfigRepository;
import com.naiterui.ehp.bs.recommend.util.Constants;
import com.naiterui.ehp.bs.recommend.util.RedisUtils;
import com.naiterui.ehp.bs.recommend.vo.crm.CrmRecomSettingVO;

/**
 * CMR推荐设置
 *
 * @author mudou
 * @since 2.9.0
 */
@Component
public class RecomSettingFunc {

    private static final Logger LOGGER = LoggerFactory.getLogger(RecomSettingFunc.class);

    /**
     * 审核开关缓存时效
     */
    private static final int RECOM_SETTING_TIMEOUT = 60 * 60;

    @Autowired
    private IRecomAuditConfigRepository recomAuditConfigRepository;

    /**
     * 初始化推荐审核设置
     * RecomSettingsFunc.defaultSetting()
     *
     * @return
     *
     * @Author mudou
     * @Date 2017年8月2日
     * @since 2.9.0
     */

    private CrmRecomSettingVO defaultSetting() {

        CrmRecomSettingVO recomSetting = new CrmRecomSettingVO();
        recomSetting.setAudit(CrmRecomSettingVO.AUDIT_TYPE_AUTO);
        recomSetting.setDelay(CrmRecomSettingVO.RECOM_DELAY_DEFAULT);
        recomSetting.setPin(CrmRecomSettingVO.RECOM_PIN_OFF);
        recomSetting.setSign(CrmRecomSettingVO.RECOM_SIGN_ON);
        recomSetting.setSafeAudit(CrmRecomSettingVO.SAFE_AUDIT_OFF);
        return recomSetting;

    }

    /**
     * 主动请求CRM刷新推荐配置
     * RecomSettingFunc.refreshSetting()
     *
     * @return
     *
     * @Author mudou
     * @Date 2017年8月2日
     * @since 2.9.0
     */

    public CrmRecomSettingVO refreshSetting() {

        CrmRecomSettingVO recomSetting = this.defaultSetting();

        try {

            // 获取初始配置
            Page<RecomAuditConfig> auditConfigPage = recomAuditConfigRepository.findAll(PageRequest.of(0, 1, Sort.by(Sort.Order.desc("id"))));
            RecomAuditConfig auditConfig = CollectionUtils.isEmpty(auditConfigPage.getContent()) ? null : auditConfigPage.getContent().get(0);
            if (auditConfig != null && RecomAuditConfig.AUDIT_TYPE_MANUAL.equals(auditConfig.getAuditType())) {
                recomSetting.setAudit(CrmRecomSettingVO.AUDIT_TYPE_MANUAL);
                recomSetting.setDelay(CrmRecomSettingVO.RECOM_DELAY_DEFAULT);
                recomSetting.setPin(CrmRecomSettingVO.RECOM_PIN_OFF);
                recomSetting.setSign(CrmRecomSettingVO.RECOM_SIGN_ON);
                recomSetting.setSafeAudit(CrmRecomSettingVO.SAFE_AUDIT_OFF);
            }

            if (null == auditConfig) {
                LOGGER.error("[刷新推荐配置] refreshRecomSetting ERROR ; recomSetting empty , use default");
                return recomSetting;
            }

            // 更新推荐审核开关配置并缓存Redis
            this.cacheRecomSetting(recomSetting);

            LOGGER.info("[刷新推荐配置] refreshRecomSetting COMPLETE ; setting={}", recomSetting.toString());

        } catch (Exception e) {
            LOGGER.error("[刷新推荐配置] refreshRecomSetting ERROR ; use default", e);
        }
        return recomSetting;

    }

    /**
     * 缓存开关设置
     * RecomSettingsFunc.cacheRecomSetting()
     *
     * @param recomSetting
     *
     * @throws BusinessException
     * @Author mudou
     * @Date 2017年8月2日
     * @since 2.9.0
     */
    public void cacheRecomSetting(CrmRecomSettingVO recomSetting) throws BusinessException {

        if (!recomSetting.validate()) {
            throw new BusinessException(ExceptionCodes.PARAM_ERROR);
        }

        LOGGER.info("[CRM同步开关配置] recomSetting info : {}", recomSetting.toString());

        RedisUtils.set(Constants.CRM_RECOM_SETTING, recomSetting, RECOM_SETTING_TIMEOUT);
    }

    /**
     * 获取CRM推荐审核开关设置
     * RecomSettingsFunc.getSetting()
     *
     * @return
     *
     * @Author mudou
     * @Date 2017年8月2日
     * @since 2.9.0
     */

    public CrmRecomSettingVO getSetting() {

        Object settingCache = RedisUtils.get(Constants.CRM_RECOM_SETTING);
        if (null == settingCache) {
            return this.refreshSetting();
        }
        CrmRecomSettingVO settingVO = (CrmRecomSettingVO) settingCache;
        return settingVO;
    }
}
